package com.wq.rentHouse.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sun.org.apache.regexp.internal.RE;
import com.wq.rentHouse.entity.UserEntity;
import com.wq.rentHouse.entity.dto.HouseDto;
import com.wq.rentHouse.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.wq.rentHouse.entity.HouseEntity;
import com.wq.rentHouse.service.HouseService;
import com.wq.common.utils.PageUtils;
import com.wq.common.utils.R;


/**
 * 房屋表
 *
 * @author wuyunpeng
 * @email 2874165407@qq.com
 * @date 2022-09-06 08:37:15
 */
@RestController
@RequestMapping("rentHouse/house" )
public class HouseController {
    @Autowired
    private HouseService houseService;

    @Autowired
    private UserService userService;

    /**
     * 列表
     */
    @RequestMapping("/list" )
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = houseService.queryPage(params);
        final List<HouseEntity> houseEntityList = (List<HouseEntity>) page.getList();
        final List<HouseDto> houseDtoList = houseEntityList.stream().map((item) -> {
            final HouseDto houseDto = getHouseDto(item);
            return houseDto;
        }).collect(Collectors.toList());
        page.setList(houseDtoList);
        return R.ok().put("page", page);
    }


    private HouseDto getHouseDto(HouseEntity houseEntity) {
        final HouseDto houseDto = new HouseDto();
        BeanUtils.copyProperties(houseEntity, houseDto);
        //renter
        final Long renterId = houseEntity.getRenterId();
        final UserEntity renter = userService.getById(renterId);
        if (renter != null) {
            houseDto.setRenterName(renter.getName());
        }
        //tenant
        final Long tenantId = houseEntity.getTenantId();
        final UserEntity tenant = userService.getById(tenantId);
        if (tenant != null) {
            houseDto.setTenantName(tenant.getName());
        }
        return houseDto;
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{id}" )
    public R info(@PathVariable("id" ) Long id) {
        HouseEntity house = houseService.getById(id);
        final HouseDto houseDto = getHouseDto(house);
        return R.ok().put("house", houseDto);
    }


    private UserEntity getUser(Long id, String name) {
        final LambdaQueryWrapper<UserEntity> lqw = new LambdaQueryWrapper<>();
        lqw.eq(UserEntity::getId, id);
        lqw.eq(UserEntity::getName, name);
        final UserEntity userEntity = userService.getOne(lqw);
        return userEntity;
    }

    /**
     * 保存
     */
    @RequestMapping("/save" )
    public R save(@RequestBody HouseDto houseDto) {
        /**
         * 户主
         */
        final Long tenantId = houseDto.getTenantId();
        final String tenantName = houseDto.getTenantName();
        final UserEntity tenantUser = getUser(tenantId, tenantName);
        /**
         * 租户
         */
        final Long renterId = houseDto.getRenterId();
        final String renterName = houseDto.getRenterName();
        UserEntity renterUser = null;
        if (renterId != null && renterId > 0) {
            renterUser = getUser(renterId, renterName);
            if (renterUser == null) {
                return R.error("该用户不存在 " );
            }
        }
        /**
         * 先判断该用户是否存在
         */

        if (tenantUser == null) {
            return R.error("该用户不存在  " );
        }

        /**
         * 如果存在，则存入数据库中,并修改 user 信息
         */
        houseService.save(houseDto);

        /**
         * 修改 user
         */
        final Long houseId = houseDto.getId();
        if (tenantUser != null) {
            String rentouts = tenantUser.getRentouts();
            if ("".equals(rentouts) || rentouts == null) rentouts = Long.toString(houseId);
            else rentouts = rentouts + "," + houseId;
            final UserEntity user = new UserEntity();
            user.setId(tenantId);
            user.setRentouts(rentouts);
            userService.updateById(user);
        }
        //
        if (renterUser != null) {
            String rents = renterUser.getRents();
            if ("".equals(rents) || rents == null) rents = Long.toString(houseId);
            else rents = rents + "," + houseId;
            final UserEntity user1 = new UserEntity();
            user1.setId(renterId);
            user1.setRents(rents);
            userService.updateById(user1);
        }
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update" )
    public R update(@RequestBody HouseDto houseDto) {
        houseService.updateById(houseDto);
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete" )
    public R delete(@RequestBody Long[] ids) {
        for (Long id : ids) {
            final LambdaQueryWrapper<HouseEntity> lqw = new LambdaQueryWrapper<>();
            lqw.eq(HouseEntity::getId, id);
            final HouseEntity house = houseService.getOne(lqw);
            //user表
            final Long tenantId = house.getTenantId();
            final Long renterId = house.getRenterId();
            //tenant
            final LambdaQueryWrapper<UserEntity> lqw2 = new LambdaQueryWrapper<>();
            lqw2.eq(UserEntity::getId, tenantId);
            final UserEntity tenant = userService.getOne(lqw2);
            String rentouts = tenant.getRentouts();
            final int index = rentouts.indexOf(Long.toString(id));
            if (index != -1) {
                // 1,2,3
                String prefix = rentouts.substring(0, index);
                String suffix = rentouts.substring(index + 2);
                rentouts = prefix + suffix;
            }
            tenant.setRentouts(rentouts);
            userService.updateById(tenant);
            //renter
            if (!"".equals(renterId) && renterId != null) {
                final LambdaQueryWrapper<UserEntity> lqw3 = new LambdaQueryWrapper<>();
                lqw3.eq(UserEntity::getId, renterId);
                final UserEntity renter = userService.getOne(lqw3);
                if (renter != null) {
                    String rents = renter.getRents();
                    final int index2 = rents.indexOf(Long.toString(id));
                    if (index2 != -1) {
                        // 1,2,3
                        String prefix = rents.substring(0, index2);
                        String suffix = rents.substring(index2 + 2);
                        rents = prefix + suffix;
                    }
                    renter.setRents(rents);
                    userService.updateById(renter);
                }
            }
        }
        houseService.removeByIds(Arrays.asList(ids));
        return R.ok();
    }

}
